package cn.lf.android.lawfirm;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.v4.app.FragmentActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.jaeger.library.StatusBarUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.lf.android.lawfirm.home.controller.EditionController;
import cn.lf.android.lawfirm.http.manager.EBCallback;
import cn.lf.android.lawfirm.http.manager.MyOkHttpClient;
import cn.lf.android.lawfirm.login.LoginActivity;
import cn.lf.android.lawfirm.login.UserAccount;
import cn.lf.android.lawfirm.login.controller.LoginController;
import cn.lf.android.lawfirm.swipefinish.SwipeFinishLayout;
import cn.lf.android.lawfirm.utils.DebugLog;
import cn.lf.android.lawfirm.utils.EmojiFilter;
import cn.lf.android.lawfirm.utils.EmptyUtil;
import cn.lf.android.lawfirm.utils.KeyBoardUtils;
import cn.lf.android.lawfirm.utils.MIUIUtils;
import cn.lf.android.lawfirm.utils.SPUtil;
import cn.lf.android.lawfirm.view.CToast;

import static cn.lf.android.lawfirm.MyApplication.context;


public abstract class BaseActivity extends FragmentActivity implements
        View.OnClickListener, SwipeFinishLayout.SwipeToCloseLayoutAction {
    /**
     * 上下文
     **/
    protected Activity mActivity;
    /**
     * 吐司
     **/
    protected Toast mToast;

    protected CToast mCToast;
    /**
     * 自定义
     **/
    protected Toast mCustomerToast;

    /**
     * 获取view布局,只支持int和view
     */
    public abstract Object getContentResView();

    /**
     * 初始化
     **/
    public abstract void initView();

    //
    public abstract void initData();

    private boolean isAnimFinish = true;

    private SwipeFinishLayout mSwipeToCloseLayout;
    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        MyApplication.registActivity(this);
        mActivity = this;
        Object o = getContentResView();
        if (o instanceof Integer) {
            setContentView((Integer) o);
        } else if (o instanceof View) {
            setContentView((View) o);
        } else {
            throw new IllegalStateException(
                    "getContentResView返回不是integer或者view类型");
        }
        initView();
        initData();
    }

    //沉浸式状态栏
    public void initActionBarWhite() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StatusBarUtil.setColor(this, getResources().getColor(R.color.white));
        }
    }

    @CallSuper
    @Override
    protected void onResume() {
        super.onResume();
        MyApplication.setCurrentActivity(this);
    }

    /**
     * 拦截创建View的事件
     *
     * @param name
     * @param context
     * @param attrs
     * @return
     */
    @Override
    public View onCreateView(String name, Context context, AttributeSet attrs) {
        //EditText的输入类型
        if (name.equals("EditText")) {
            //处理一般输入框的emoji过滤 没有设置inputtype或者为text的输入框
            EditText editText = new EditText(context, attrs);

            int inputType = editText.getInputType();
            if (inputType == InputType.TYPE_CLASS_TEXT
                    || inputType == 0
                    || inputType == 131073) {
                InputFilter[] filters = editText.getFilters();
                InputFilter emojiInputFilter = new InputFilter() {
                    @Override
                    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                        if (!source.equals("")) {
                            return EmojiFilter.filterEmoji2(source.toString());
                        }
                        return "";
                    }
                };

                if (filters != null) {
                    InputFilter[] myfilters = new InputFilter[filters.length + 1];
                    for (int i = 0; i < filters.length; i++) {
                        myfilters[i] = filters[i];
                    }
                    myfilters[myfilters.length - 1] = emojiInputFilter;
                    editText.setFilters(myfilters);
                } else {
                    editText.setFilters(new InputFilter[]{emojiInputFilter});
                }
            }
            return editText;
        } else {
            return super.onCreateView(name, context, attrs);
        }
    }


    /**
     * 检查网络是否可用
     * <p>
     * 该方法写在每次网络请求的点击事件监听里(无网络会Tosat提示)
     * <p>
     * true表示提交的时候判断
     * <p>非列表页使用
     * return true表示没有网络
     */
    public boolean checkNetWork(boolean submit) {
        if (!isNetWorkConnected()) {
            if (submit) {
                customShortToast(R.string.network_submit_toast);
            } else {
                customShortToast(R.string.network_unline_toast);
            }
            return true;
        }

        return false;
    }

    /**
     * 显示自定义短Toast并且修改文字但不累加（一般情况调用此方法即可）
     *
     * @param msg int类型(R.String.)
     */
    public void customShortToast(int msg) {
        showCToast(msg);
//		customToast(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 显示自定义短Toast并且修改文字但不累加（一般情况调用此方法即可）
     *
     * @param msg String类型
     */
    public void customShortToast(String msg) {
        showCToast(msg);
//		customToast(msg, Toast.LENGTH_SHORT);
    }

    /**
     * 1.2新加  1.5s 吐司
     *
     * @param msg
     */
    public void showCToast(String msg) {
        permission(msg);
    }

    /**
     * 1.2新加  1.5s 吐司
     */
    public void showCToast(int msg) {
        permission(msg);
    }

    public void permission(int msg) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (MIUIUtils.isMIUI()) {
                customToast(msg, Toast.LENGTH_SHORT);
            } else {
                //Android6.0以上
                mCToast = CToast.makeText(mActivity, msg, 1500);
                mCToast.show();
            }
        } else {
            //Android6.0以下，不用动态声明权限
            mCToast = CToast.makeText(mActivity, msg, 1500);
            mCToast.show();
        }
    }

    private void customToast(int msg, int duration) {
        View layout = LayoutInflater.from(mActivity).inflate(R.layout.toast_bg,
                null);
        TextView text = (TextView) layout.findViewById(R.id.txt_toast);
        text.setText(msg);
        if (mCustomerToast == null) {
            mCustomerToast = new Toast(mActivity);
        }
        mCustomerToast.setGravity(Gravity.CENTER, 0, 0);
        mCustomerToast.setDuration(duration);
        mCustomerToast.setView(layout);
        mCustomerToast.show();
    }

    public void permission(String msg) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (MIUIUtils.isMIUI()) {
                customToast(msg, Toast.LENGTH_SHORT);
            } else {
                //Android6.0以上
                mCToast = CToast.makeText(mActivity, msg, 1500);
                mCToast.show();
            }
        } else {
            //Android6.0以下，不用动态声明权限
            mCToast = CToast.makeText(mActivity, msg, 1500);
            mCToast.show();
        }
    }

    private void customToast(String msg, int duration) {
        View layout = LayoutInflater.from(mActivity).inflate(R.layout.toast_bg,
                null);
        TextView text = (TextView) layout.findViewById(R.id.txt_toast);
        text.setText(msg);
        if (mCustomerToast == null) {
            mCustomerToast = new Toast(mActivity);
        }
        mCustomerToast.setGravity(Gravity.CENTER, 0, 0);
        mCustomerToast.setDuration(duration);
        mCustomerToast.setView(layout);
        mCustomerToast.show();
    }

    /**
     * 判断网络连接
     * 列表页请求时使用
     *
     * @return
     */
    protected boolean isNetWorkConnected() {
        ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo net = conn.getActiveNetworkInfo();
        if (net != null && net.isConnected()) {
            return true;
        }
        return false;
    }

    /**
     * 此方法要在setContentView之后执行，用户添加右滑退出的布局。
     */
    public void addSwipeFinishLayout() {
        mSwipeToCloseLayout = new SwipeFinishLayout(this);
        mSwipeToCloseLayout.attachToActivity(this);
        mSwipeToCloseLayout.setSwipeToCloseLayoutAction(this);
    }

    /**
     * 是否可滑动退出
     *
     * @param enableGesture
     */
    public void setEnableGesture(boolean enableGesture) {
        if (mSwipeToCloseLayout != null) {
            mSwipeToCloseLayout.setEnableGesture(enableGesture);
        }
    }

    /**
     * 全屏时滑动的处理
     *
     * @param fullScreen
     */
    public void setActivityFullScreen(boolean fullScreen) {
        if (mSwipeToCloseLayout != null) {
            mSwipeToCloseLayout.setActivityFullScreen(fullScreen);
        }
    }

    /**
     * 可以设置关闭退出动画
     *
     * @param isAnimFinish
     */
    public void setAnimFinish(boolean isAnimFinish) {
        this.isAnimFinish = isAnimFinish;
    }

    /**
     * 向右滑动是否可关闭activity
     */
    @Override
    public boolean onScrollToClose() {
        return true;
    }

    /**
     * 是否点击在可左右滑动的views里面
     */
    @Override
    public boolean inChild(Rect rect, Point point) {
        return false;
    }

    @Override
    public void onCloseAction() {
        setResult(998899);
        finish();
    }

    protected ProgressDialog bar;

    /**
     * 显示默认ProgressBar
     */
    public void showProgressDia() {
        if (bar == null) {
            try {
                bar = ProgressDialog.show(this, null, null);
                bar.setProgressStyle(R.style.ProgressDialog);
                bar.setContentView(R.layout.taste_loading);
            } catch (Exception e) {
            }

        }
    }

    /**
     * 取消ProgressBar
     */
    public void dismissProgressDia() {
        if (bar != null && bar.isShowing()) {
            try {
                bar.dismiss();

            } catch (Exception e) {
            }
            bar = null;
        }
    }

    // 隐藏输入键盘
    public void hintKbTwo() {
        KeyBoardUtils.hideSoftInput(mActivity);
    }

    @Override
    protected void onDestroy() {
        MyApplication.removeActivity(this);
        super.onDestroy();
    }

    public void reLogin() {
        SPUtil sp = new SPUtil(this);
        UserAccount userAccount = sp.getUserAccount();
        if (null != userAccount) {
            EBCallback.ALREADY_REQUEST_LOGIN = false;
            Map<String, String> params = new HashMap<String, String>();
            params.put("UserName", userAccount.getUserName());
            params.put("Password", userAccount.getPassword());
            new MyOkHttpClient().doGet(AppConfig.LOGIN, params, new EBCallback(false) {

                @Override
                public void onEBResponse(String response) {
                    JSONObject myJsonObject;
                    JSONObject responsObject;
                    Boolean isSuc;
                    String accessToken;
                    try {
                        myJsonObject = new JSONObject(response);
                        isSuc = myJsonObject.getBoolean("isSuc");
                        responsObject = myJsonObject.getJSONObject("responsObject");
                        accessToken = responsObject.getString("accessToken");
                        if (isSuc) {
                            SPUtil spUtil = new SPUtil(context);
                            UserAccount userAccount = new UserAccount();
                            userAccount.setUserName(userAccount.getUserName());
                            userAccount.setPassword(userAccount.getPassword());
                            spUtil.setAccountInfo(userAccount);
                            spUtil.setAccessToken("Bearer " + accessToken);
                            //成功
                            EBCallback.reCallBySession();
                            EBCallback.ALREADY_REQUEST_LOGIN = false;
                        } else {
                            //shibai
                            EBCallback.AUTO_REQUEST_QUEUE_BY_SESSION.clear();
                            //返回登录页
                            backToLoginActivty();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
//                        dismissProgressDia();
                }

                @Override
                public void onEBError(String errorMsg) {
                    //shibai
                    EBCallback.AUTO_REQUEST_QUEUE_BY_SESSION.clear();
                    //返回登录页
                    backToLoginActivty();
                }
            });
        } else {
            EBCallback.AUTO_REQUEST_QUEUE_BY_SESSION.clear();
            backToLoginActivty();
        }

    }

    public void backToLoginActivty() {
        MyApplication.finishAllActivity();
        startActivity(new Intent(this, LoginActivity.class));
    }

}
